import store from "../store";
import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/Login";
import Register from "../views/Register";
import User from "../views/User";
import Files from "../views/Files";
import {auth} from "../common/cloudbase";

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    name:"Login",
    component: Login
  },
  {
    path: "/files",
    name:"Files",
    meta:{
      auth: true
    },
    component: Files
  },
  {
    path: "/user",
    name:"User",
    meta:{
      auth: true
    },
    component: User
  },
  {
    path: "/register",
    name:"Register",
    meta:{
      auth: false
    },
    component: Register
  },
  {
    path: "/about",
    name: "About",
    meta:{
      auth: true
    },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
  },
  {
    path: "/",
    meta: {
      auth: true
    },
    redirect:'/user'
  }
];

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes,
});


router.beforeEach(async(to,from,next)=>{
  let userChecked = store.state.userChecked;
  let user =  store.state.user;
  let isAuth = to.meta.auth;
  if(!isAuth){
    next();
    return;
  }

  if(userChecked === false){
    // 初始化获取用户
    try{
      user = await auth.getCurrenUser();
      console.log(user);
      store.commit("setUserData",user);
      if(user){
        store.commit("setUserChecked",true);
      }
    }catch(err){
      console.log(err);
      alert("初始化失败。您无法使用此系统");
      return;
    }
  }
  if(!user){
    console.log(user);
    alert("请先登录");
    next('/login');
  }
  next();
})
export default router;
